package com.main.toyexchange;

/*
 * 发布玩具的activity
 * 用户需要选择发布玩具的照片，填写玩具名称、新旧程度、详细描述等
 */

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bjtu.toyexchange.R;
import com.util.toyexchange.DialogUtil;
import com.util.toyexchange.HttpUtil;

public class FabuActivity extends Activity implements OnClickListener{
	private static final String TAG = "uploadImage";
    private static String requestURL = "http://www.echuandan.com/geobdImage";
    private Button fabu_toy;
    private ImageView imageView, cho_pic;
    private EditText toy_name, toy_deg, toy_det;
    private String toyname, toydeg, toydet, username;
     
    private String picPath = "1";
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fabu);
        
        //接受到用户名
        Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		
		username = bundle.getString("username");
        
        cho_pic = (ImageView) this.findViewById(R.id.cho_pic);
        cho_pic.setOnClickListener(this);
        
        fabu_toy = (Button) this.findViewById(R.id.fabu_toy);
        fabu_toy.setOnClickListener(this);
        
        imageView = (ImageView) this.findViewById(R.id.cho_pic);
    }
     
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        
        //从相册中选择玩具的照片的按钮
        case R.id.cho_pic:            
             //这个是调用android内置的intent，来过滤图片文件   ，同时也可以过滤其他的             
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, 1);
            
//            //上传照片
//            File file = new File(picPath);
//            if(file!=null)
//            {
//                String request = UploadUtil.uploadFile( file, requestURL);
//                cho_pic.setText(request);
//            }
            
            break;
            
        //发布玩具的按钮
        case R.id.fabu_toy:
            
            //得到输入的玩具的名称，新旧程度，详细描述
            toy_name = (EditText)FabuActivity.this.findViewById(R.id.toy_name_v);
    		toyname = toy_name.getText().toString();
    		
    		toy_deg = (EditText)FabuActivity.this.findViewById(R.id.toy_deg_v);
    		toydeg = toy_deg.getText().toString();
    		
    		toy_det = (EditText)FabuActivity.this.findViewById(R.id.toy_det_v);
    		toydet = toy_det.getText().toString();
        	
        	//输入的信息的非空校验
        	if (("").equals(toyname) || null == toyname) {
				Toast.makeText(FabuActivity.this,"玩具名称不能为空...",100).show();
				return;
			}
			else if (("").equals(toydeg) || null == toydeg) {
				Toast.makeText(FabuActivity.this,"玩具新旧程度不能为空...",100).show();
				return;
			}
			else if (("").equals(toydet) || null == toydet) {
				Toast.makeText(FabuActivity.this,"玩具详细描述不能为空...",100).show();
				return;
			}
			else {
				if(publishPro())
				{
					Toast.makeText(FabuActivity.this, "发布玩具"+toyname+"成功...", 200).show();
					
				}
			}
        	
            break;
            
        default:
            break;
        }
    }
 
    //向服务器端发送玩具信息
    private boolean publishPro(){
    	JSONObject jsonObj;
		try
		{
			jsonObj = query();
			// 如果userId 大于0
			if (jsonObj.getInt("toyId") > 0)
			{
				return true;
			}
			else
				DialogUtil.showDialog(this
						, "发布玩具失败！", false);
		}
		catch (Exception e)
		{
			DialogUtil.showDialog(this
				, "服务器响应异常，请稍后再试！", false);
			e.printStackTrace();
		}

		return false;
    }
    
    // 定义发送请求的方法
	private JSONObject query()
		throws Exception
	{
		// 使用Map封装请求参数
		Map<String, String> map = new HashMap<String, String>();
		map.put("tname", toyname);
		map.put("tlevel", toydeg);
		map.put("tdescription", toydet);
		map.put("uname", username);
		map.put("tphoto", picPath);
		// 定义发送请求的URL
		String url = HttpUtil.BASE_URL + "PublishServlet";
		// 发送请求
		JSONObject jb = new JSONObject(HttpUtil.postRequest(url, map)); 
		return jb;
	}
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==Activity.RESULT_OK)
        {
            /**
             * 当选择的图片不为空的话，在获取到图片的途径 
             */
            Uri uri = data.getData();
            Log.e(TAG, "uri = "+ uri);
            try {
                String[] pojo = {MediaStore.Images.Media.DATA};
                 
                Cursor cursor = managedQuery(uri, pojo, null, null,null);
                if(cursor!=null)
                {
                    ContentResolver cr = this.getContentResolver();
                    int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(colunm_index);
                    /***
                     * 这里加这样一个判断主要是为了第三方的软件选择，比如：使用第三方的文件管理器的话，你选择的文件就不一定是图片了，这样的话，我们判断文件的后缀名
                     * 如果是图片格式的话，那么才可以  
                     */
                    if(path.endsWith("jpg")||path.endsWith("png"))
                    {
                        picPath = path;
                        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                        imageView.setImageBitmap(bitmap);
                    }else{alert();}
                }else{alert();}
                 
            } catch (Exception e) {
            }
        }
         
        super.onActivityResult(requestCode, resultCode, data);
    }
     
    private void alert()
    {
        Dialog dialog = new AlertDialog.Builder(this)
        .setTitle("提示")
        .setMessage("您选择的不是有效的图片")
        .setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        picPath = null;
                    }
                })
        .create();
        dialog.show();
    }
}